package com.combetter.changxing.ui.base;

import android.Manifest;
import android.arch.lifecycle.AndroidViewModel;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.databinding.ViewDataBinding;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;

import com.combetter.changxing.R;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Mark.fan on 2018/6/11.
 */

public abstract class BleScanFragment<T extends ViewDataBinding,V extends AndroidViewModel> extends BaseFragment<T, V> implements BluetoothAdapter.LeScanCallback {
    private static final int REQUEST_CODE_ACCESS_COARSE_LOCATION = 1;
    private BluetoothAdapter mAdapter;

    public static final int REQUEST_ENABLE_BT = 1001;

    //10秒钟后停止扫描
    private static final long SCAN_PERIOD = 10000;

    private boolean mScan = false;

    private Handler mHandler;

    @Override
    public void init() {
        if (!mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(mContext, R.string.ble_not_supported, Toast.LENGTH_LONG).show();
            getBaseActivity().finish();
        }
        ActivityCompat.requestPermissions(getBaseActivity(), new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE_ACCESS_COARSE_LOCATION);
        initBle();
    }

    private void initBle() {
        BluetoothManager manager = (BluetoothManager) getBaseActivity().getSystemService(Context.BLUETOOTH_SERVICE);
        mAdapter = manager.getAdapter();

        if (mAdapter == null || !mAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        }
        mHandler = new Handler();
    }

    public void scanLeDevice(final boolean enable) {
        if (enable) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScan = false;
                    mAdapter.stopLeScan(BleScanFragment.this);
                }
            }, SCAN_PERIOD);
            mScan = true;
            mAdapter.startLeScan(BleScanFragment.this);
        } else {
            mScan = false;
            mAdapter.stopLeScan(BleScanFragment.this);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ACCESS_COARSE_LOCATION: {
                Map<String, Integer> perms = new HashMap<String, Integer>();
                perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);
                // Check for ACCESS_FINE_LOCATION
                if (perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                    initBle();
                } else {
                    Toast.makeText(mContext, "One or More Permissions are DENIED Exiting App :(", Toast.LENGTH_SHORT).show();
                    getBaseActivity().finish();
                }
            }
            break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
}
